<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/29
 * Time: 11:03
 */

namespace app\index\controller;
use app\index\model\Goods as GoodsModel;
use think\Build;
use think\Db;
use think\Model;
use think\Request;
use think\Url;
use page\Page;
class Goods
{
    /**
     * @param Request $request
     * @return array
     * 商品列表
     */
    public function index2(Request $request)
    {
        $param = $request->param();
        $order = ['sg.sort' => 'asc','sg.id' => 'desc'];
        if (!empty($param['order'])) $order = [$param['order'] => 'asc'];
        $condition['sg.state'] = ['eq', 1];
        $condition['sg.auding_status'] = ['eq', 2];
        $condition['sg.is_delete'] = ['eq', 1];
        if (!empty($param['low_price'])) $condition['sg.price'] = ['egt', $param['low_price']];
        if (!empty($param['high_price'])) $condition['sg.price'] = ['elt', $param['high_price']];
        if (!empty($param['goods_name'])) $condition['sg.title'] = ['like', '%' . $param['goods_name'] . '%'];
        if (!empty($param['type_id'])) $condition['sg.goods_id'] = ['eq', $param['type_id']];
        $data = Db::name('shop_goods sg')
            ->field('sg.id,sg.title,sg.price,sg.picUrl,sg.sale_number')
            ->join('shop_spec_attr ssa', 'ssa.goods_id = sg.id')
            ->where('ssa.shop_id', 'neq', 0)
            ->where($condition)->order($order)
            ->group('ssa.goods_id')
            ->paginate(6)->toArray();

        $data2 = Db::name('shop_goods sg')
            ->field('sg.id,sg.title,sg.price,sg.picUrl,sg.sale_number')
            ->join('shop_spec_attr ssa', 'ssa.goods_id = sg.id')
            ->where('ssa.shop_id', 'neq', 0)
            ->where($condition)->order($order)
            ->group('ssa.goods_id')
            ->paginate(10000);
        return ['code' => 200, 'message' => '商品列表', 'data' => $data,'data2' => $data2];
    }
    public function index(Request $request)
    {
        $param = $request->param();
        $order = ['sg.sort' => 'asc','sg.id' => 'desc'];
        if (!empty($param['order'])) $order = [$param['order'] => 'asc'];
        $condition['sg.state'] = ['eq', 1];
        $condition['sg.auding_status'] = ['eq', 2];
        $condition['sg.is_delete'] = ['eq', 1];
        if (!empty($param['low_price'])) $condition['sg.price'] = ['egt', $param['low_price']];
        if (!empty($param['high_price'])) $condition['sg.price'] = ['elt', $param['high_price']];
        if (!empty($param['goods_name'])) $condition['sg.title'] = ['like', '%' . $param['goods_name'] . '%'];
        if (!empty($param['type_id'])) $condition['sg.goods_id'] = ['eq', $param['type_id']];
        $data = Db::name('shop_goods sg')
            ->field('sg.id,sg.title,sg.price,sg.picUrl,sg.goods_sale sale_number')
            ->join('shop_spec_attr ssa', 'ssa.goods_id = sg.id')
            ->where('ssa.shop_id', 'neq', 0)
            ->where($condition)->order($order)
            ->group('ssa.goods_id')
            ->paginate(10000)->toArray();
        $single103 = Db::name('single')
            ->where('id', 103)
            ->where('auding_status',2)
            ->where('is_delete',1)
            ->where('status',1)
            ->field('id,cat_name title,pic_url picUrl,count sale_number,price')
            ->select()->toArray();
        $single103[0]['id'] = 99999;
        if (is_null($single103)) $single103 = [];
        $data = array_merge($single103,$data['data']);
        $page = new Page(count($data), 6000, Request::instance()->param());
        $page_html = $page->show($data);// 分页显示输 __FUNCTION__
        $data2 = Db::name('shop_goods sg')
            ->field('sg.id,sg.title,sg.price,sg.picUrl,sg.sale_number')
            ->join('shop_spec_attr ssa', 'ssa.goods_id = sg.id')
            ->where('ssa.shop_id', 'neq', 0)
            ->where($condition)->order($order)
            ->group('ssa.goods_id')
            ->paginate(10000)->toArray();
        return ['code' => 200, 'message' => '商品列表', 'data' => $page_html,'data2' => $data];
    }



    /**
     * @param $id
     * @return array
     * 商品详情
     */
    public function view($member_id = 0,$id,$longitude = '0',$latitude ='0',$shop_id = 0)
    {
        //126.535319 44.579445
        $public_condition['auding_status'] = ['eq',2];//审核通过
        $info = Db::name('shop_goods')
            ->alias('g')
            ->join('shop_spec_attr a','g.id = a.goods_id')
            ->join('shop s','a.shop_id = s.id')
            ->field('g.id,g.title,g.price,g.market_price,g.picArr,a.inventory,s.shop_name,s.shop_address,s.shop_phone')
            ->select($id);
        $info = Db::name('shop_goods')
            ->alias('g')
            ->field('g.id,g.title,g.price,g.market_price,g.picArr,g.content,g.buy_must_know')
            ->join('shop_spec_attr a','g.id = a.goods_id')
            ->find($id);
        $info['picArr'] = unserialize($info['picArr']) ? unserialize($info['picArr']) : [];
        $list = Db::name('shop_spec_attr')
            ->alias('a')
            ->where('a.goods_id',$id)
            ->field('a.goods_id,a.shop_id,s.shop_title shop_name,s.shop_address,s.shop_phone,s.thumbnail pic_url,s.longitude,s.latitude')
            ->join('shop s','a.shop_id = s.id')
            ->where('s.is_delete',1)
            ->where('s.auding_status',2)
            ->group('shop_id')
            ->select()->toArray();
        if(!empty($list)){
            foreach ($list as $k => &$v){
                $v['inventory'] = Db::name('shop_spec_attr')->where('shop_id',$v['shop_id'])->where('goods_id',$v['goods_id'])->sum('inventory');
            }
        }
        if($shop_id == 0) $shop_id = $list[0]['shop_id'];
        $info['inventory'] = Db::name('shop_spec_attr')->where('goods_id',$id)->where('shop_id',$shop_id)->sum('inventory');
        $info['list'] = $list;
        $info['content_url'] = Request::instance()->domain().Url::build('web',['id' => $id,'field' => 'content']);
        $info['buy_must_know_url'] = Request::instance()->domain().Url::build('web',['id' => $id,'field' => 'buy_must_know']);
        foreach ($info['list'] as $k => &$v){
            //$info['list'][$k]['distance'] = round(getDistance($v['longitude'],,(float)$longitude,(float)$latitude),1);
            $info['list'][$k]['distance'] = (new Shop())->distance($latitude,$longitude,$v['latitude'],$v['longitude']);
        }
        if(!empty($member_id)){
            $goods_history = Db::name('goods_history')->where('goods_id',$id)->where('member_id',$member_id)->find();
            if(empty($goods_history)){
                Db::name('goods_history')->insert(['goods_id' => $id,'create_time' => date('Y-m-d',time()),'member_id' => $member_id]);
            }

        }
        if(!empty($member_id)) { //登录
            $auding_status['single_id'] = ['eq',$id];
            $auding_status['oe.member_id'] = ['eq',$member_id];
           //$others_evaluate['auding_status'] = ['eq', 2];
            //$others_evaluate['single_id'] = ['eq', $id];
            $others_evaluate = function ($query) use ($id) {
                $query->where('auding_status', 'eq', '2')->where('single_id', 'eq', $id);
            };
            $info['evaluate_count'] = Db::name('order_evaluate oe')->fetchSql(false)->where($auding_status)->whereOr($others_evaluate)->count();
            //halt($info['evaluate_count']);
            $info['list_evaluate'] = Db::name('order_evaluate oe')
                ->join('member m', 'oe.member_id = m.id','left')
                ->where($auding_status)->whereOr($others_evaluate)
                ->field('oe.*,DATE_FORMAT(oe.create_time,"%Y-%m-%d") create_time,oe.pic_url,m.username,m.nickname,m.avatar head_pic')
                ->order('oe.id','desc')
                ->where('single_id', $id)->paginate(10);
//            $auding_status['auding_status'] = ['eq', 1];
//            $auding_status['member_id'] = ['eq', $member_id];
//            $others_evaluate['auding_status'] = ['eq', 2];
//            $others_evaluate['single_id'] = ['eq', $id];
//            $evaluate = function ($query) use ($id,$member_id) {
//                $query->whereOr(['member_id' => $member_id,'single_id' => $id])->whereOr(['single_id' => $id,'auding_status' => 2]);
//            };
//            //$evaluate['member_id'] = ['eq',$member_id];//当前会员的评价条件 2合1
//            //$evaluate['single_id'] = ['eq',$id];//当前会员的评价条件 2合1
        }else{
            $info['evaluate_count'] = Db::name('order_evaluate oe')->where('single_id', $id)->where('auding_status',2)->count();
            $info['list_evaluate'] = Db::name('order_evaluate oe')
                ->join('member m', 'oe.member_id = m.id','left')
                ->order('oe.id','desc')
                ->field('oe.*,DATE_FORMAT(oe.create_time,"%Y-%m-%d") create_time,oe.pic_url,m.username,m.nickname,m.avatar head_pic')
                ->where('auding_status',2)
                ->where('single_id', $id)->paginate(10);
//            $evaluate['auding_status'] = ['eq', 2];
//            $evaluate['single_id'] = ['eq', $id];
        }

        $cart_count = Db::name('cart')->where('member_id',$member_id)->where('type','cart')->count();//购物车商品数量，跟本接口没直接关系
        return ['code' => 200,'message' => '商品详情','data' => $info,'cart_count' => $cart_count];
    }

    /**
     * @param int $member_id
     * @param $id
     * @param $order_type
     * @return array
     * 3种订单评价
     */
    public function evaluate_list($member_id = 0, $id, $order_type)
    {
        if (!empty($member_id)) {
            if($order_type == 2) {
                $auding_status['shop_id'] = ['eq', $id];
                $auding_status['oe.member_id'] = ['eq', $member_id];
                $others_evaluate = function ($query) use ($id) {
                    $query->where('auding_status', 'eq', '2')->where('shop_id', 'eq', $id);
                };
            } else {
                $auding_status['single_id'] = ['eq', $id];
                $auding_status['oe.member_id'] = ['eq', $member_id];
                $others_evaluate = function ($query) use ($id) {
                    $query->where('auding_status', 'eq', '2')->where('single_id', 'eq', $id);
                };
            }

            $evaluate_list = Db::name('order_evaluate oe')
                ->join('member m', 'oe.member_id = m.id', 'left')
                ->where($auding_status)->whereOr($others_evaluate)
                ->where('order_type', $order_type)
                ->field('oe.*,m.username,m.head_pic')
                ->order('oe.id', 'desc')
                ->paginate(6)->toArray();

            foreach ($evaluate_list['data'] as $k => &$v) {
                $v['username'] = hideStr($v['username'], 3, 4);
            }
            $evaluate_count = Db::name('order_evaluate oe')
                ->where($auding_status)->whereOr($others_evaluate)
                ->where('order_type', $order_type)
                ->count('id');

        } else {
            $evaluate_list = Db::name('order_evaluate oe')
                ->join('member m', 'oe.member_id = m.id')
                ->where('single_id', $id)
                ->where(['auding_status' => 2])
                ->where('order_type', $order_type)
                ->field('oe.*,m.username,m.head_pic')
                ->order('oe.id', 'desc')
                ->paginate(6)->toArray();
            foreach ($evaluate_list['data'] as $k => &$v) {
                $v['username'] = hideStr($v['username'], 3, 4);
            }
            $evaluate_count = Db::name('order_evaluate oe')
                ->where('order_type', $order_type)
                ->where('single_id', $id)
                ->where(['auding_status' => 2])
                ->count('id');
        }
        return ['code' => 200, 'message' => '评论列表', 'evaluate_count' => $evaluate_count, 'evaluate_list' => $evaluate_list];
    }

    /**
     * @param $member_id
     * @return array
     * 浏览记录列表
     */
    public function history_index($member_id)
    {
        $data = Db::name('goods_history gh')
            ->join('shop_goods g', 'gh.goods_id = g.id')
            ->field('gh.create_time')
            ->where('gh.member_id', $member_id)
            ->group('gh.create_time')
            ->order('gh.create_time', 'desc')
            ->paginate(6)->toArray();
        foreach ($data['data'] as $k => &$v) {
            $v['goods_list'] = Db::name('goods_history gh')
                ->join('shop_goods g', 'gh.goods_id = g.id')
                ->field('g.id,g.title,g.price,g.picUrl')
                ->where('gh.member_id', $member_id)
                ->where('gh.create_time', $v['create_time'])
                ->select();
        }
        return ['code' => 200, 'message' => '商品历史记录', 'data' => $data];
    }

    /**
     * @param $member_id
     * @param $goods_id
     * @return array
     * 浏览记录删除
     */
    public function delete_goods_history($member_id,$goods_id){
        $ret = Db::name('goods_history')->where(['member_id' => $member_id,'goods_id' => $goods_id])->delete();
        if($ret){
            return ['code' =>200,'message' => '删除成功'];
        }
        return ['code' =>400,'message' => '失败'];
    }

    /**
     * @param $member_id
     * @return array
     * 删除所有记录
     */
    public function delete_all($member_id){
        $ret = Db::name('goods_history')->where(['member_id' => $member_id])->delete();
        if($ret){
            return ['code' =>200,'message' => '删除全部浏览记录成功'];
        }
        return ['code' =>400,'message' => '失败'];
    }

    public function attr_list($goods_id,$shop_id,$type = 'cart',$attribute = '')
    {

        $attr_list = Db::name('shop_goods a')
            ->where('a.id',$goods_id)
            ->where('b.shop_id',$shop_id)
            ->join('shop_spec_attr b','a.id = b.goods_id')
            ->field('a.id,b.price,sum(b.inventory) inventory,a.goods_attr')
            ->order('b.id','desc')
            ->find();
        if($attr_list['price'] == 0){
            $attr_list['price'] = Db::name('shop_goods')->where('id',$goods_id)->value('price');
        }
        $price = Db::name('shop_spec_attr')->where('goods_id', $goods_id)->order('id','asc')->where('attribute',$attribute)->value('price');
        if($attr_list['price'] == 0){
            $attr_list['price'] = Db::name('shop_goods')->where('id', $goods_id)->value('price');
        }
        //$attr_list['goods_attr'] = unserialize($attr_list['goods_attr']);
         $attr_list['goods_attr'] = arrayChange(unserialize($attr_list['goods_attr']),'title','list');
//        foreach ($attr_list['goods_attr'] as $k => $v){
//            echo $k.'<br/>';
//            foreach ($v as $k1 => $v1){
//                echo $v1.'-';
//            }
//        }

        return ['code' => 200,'message' => '商品详情属性值','data' => $attr_list,'shop_id' => $shop_id,'type' => $type];

    }

    public function shop_spec_attr($goods_id, $shop_id, $attribute)
    {
        $inventory = Db::name('shop_spec_attr')->where('goods_id', $goods_id)->where('shop_id', $shop_id)->where('attribute', $attribute)->value('inventory');
        $price = Db::name('shop_spec_attr')->where('goods_id', $goods_id)->order('id','asc')->where('attribute',$attribute)->value('price');
        if($price == 0){
            $price = $price = Db::name('shop_goods')->where('id', $goods_id)->value('price');
        }
        if ($inventory > 0) {
            return ['code' => 200, 'message' => 'ok', 'inventory' => $inventory,'price' => $price];
        } else {
            return ['code' => 400, 'message' => '该属性不存在或库存为0'];
        }

    }

    public function web($id,$field)
    {
        $data  = '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">';
        $data .= '<style> img {vertical-align:middle; width:auto; max-width:100%;} </style>';
        $data .= Db::name('shop_goods')->where('id',$id)->value($field);
        return response($data);
    }




}